﻿using IOP.Models;
using IOP.Protocols.MQTT.Package;
using System;

namespace IOP.Pulsar.MQTT.Abstractions
{
    public class CachePublishPackage : IDisposable
    {
        /// <summary>
        /// 发布包
        /// </summary>
        public readonly PublishPackage Package;
        /// <summary>
        /// 重复任务
        /// </summary>
        public readonly RepeatTask RepeatTask;
        /// <summary>
        /// 任务结束事件
        /// </summary>
        public event Action<ushort> TaskFinish;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="package"></param>
        /// <param name="repeatTask"></param>
        public CachePublishPackage(PublishPackage package, RepeatTask repeatTask)
        {
            Package = package;
            RepeatTask = repeatTask;
            RepeatTask.OnRunningInterrupt = OnTaskInterupt;
            RepeatTask.OnRunningFinish = OnTaskFinish;
        }

        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="taskHandle"></param>
        public void RunTask(Action taskHandle)
        {
            RepeatTask.RunTask(taskHandle);
        }

        /// <summary>
        /// 重复任务中断
        /// </summary>
        private void OnTaskInterupt()
        {
            TaskFinish(Package.PacketIdentifier);
        }

        /// <summary>
        /// 任务完成
        /// </summary>
        private void OnTaskFinish()
        {
            throw new MQTTSendException(Package, "publish package send failed");
        }

        /// <summary>
        /// 销毁资源
        /// </summary>
        public void Dispose()
        {
            TaskFinish = null;
            RepeatTask.Dispose();
        }
    }
}
